package com.wanxi.controller;

import com.wanxi.domain.ResultModel;
import com.wanxi.domain.user.UserModel;
import com.wanxi.service.user.IUserService;
import com.wanxi.util.Base64Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RequestMapping("login")
@CrossOrigin(allowCredentials = "true",origins = "http://localhost:63342",allowedHeaders = "*")
@Controller
public class LoginController extends HttpServlet {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    @ResponseBody
//    public ResultModel checkLogin(@RequestBody UserModel userInfo,@SessionAttribute("sessionCode")String sessionCode){
    public Object checkLogin(@RequestBody UserModel userInfo, HttpServletRequest request, HttpServletResponse response){
//        Object sessionCode = request.getSession().getAttribute("sessionCode");
        Object redisCode = redisTemplate.opsForValue().get("Code");

        System.out.println("存放在session中的验证码："+redisCode);

        ResultModel m= new ResultModel();
        System.out.println(userInfo.getCode());
        //获取存放在session中的验证码
        if(userInfo.getCode()==null || userInfo.getCode().equals("")){
            m.setMsg("code-error");
            return m;
        }
        if (!userInfo.getCode().equalsIgnoreCase(redisCode.toString())){
            m.setMsg("code-error");
            return m;
        }


        //密码加密
        userInfo.setPassword(Base64Code.enCode(userInfo.getPassword()));

        //得到校验结果
//        ResultModel resultModel = userService.checkLogin(userInfo);
        UserModel userModel = userService.checkLogin(userInfo);

        if (userModel != null){
            response.setHeader("username",userModel.getUsername());
            redisTemplate.opsForValue().set(userModel.getUsername(),"true");
//            redisTemplate.opsForValue().set("login","true");
            m.setMsg("success");
            m.setData(userModel);
        }else{
            m.setMsg("error");
        }

        return m;
    }


}
